import { defineStore } from 'pinia'

const DEFAULT_ORDERS = []

export const useOrderStore = defineStore('orderStore', {
  state: () => ({
    orders: [],
    initialized: false
  }),

  actions: {
    initialize() {
      if (!this.initialized) {
        const storedOrders = localStorage.getItem('orders')
        this.orders = storedOrders ? JSON.parse(storedOrders) : DEFAULT_ORDERS
        if (!storedOrders) {
          this.persist()
        }
        this.initialized = true
      }
    },

    addOrder(order) {
      this.orders.push(order)
      this.persist()
    },

    updateOrder(updated) {
      const index = this.orders.findIndex(o => o.orderNumber === updated.orderNumber)
      if (index !== -1) {
        this.orders[index] = { ...updated }
        this.persist()
      }
    },

    deleteOrder(orderNumber) {
      this.orders = this.orders.filter(o => o.orderNumber !== orderNumber)
      this.persist()
    },

    persist() {
      localStorage.setItem('orders', JSON.stringify(this.orders))
    }
  }
}) 